﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.WindowsPhoneCloud.Phone
{
    using System;
    using System.Collections.Generic;
    using System.Data.Services.Client;
    using System.Globalization;
    using System.IO.IsolatedStorage;
    using System.Windows;
    using System.Windows.Threading;
    using Microsoft.Phone.Shell;
    using Microsoft.Samples.WindowsPhoneCloud.Phone.Push;
    using Microsoft.Samples.WindowsPhoneCloud.StorageClient.Credentials;

    public class CloudClientFactory : ICloudClientFactory
    {
        private readonly IDictionary<string, object> phoneState;
        private readonly IDictionary<string, object> isolatedStorage;
        private readonly IDictionary<object, object> appResources;
        private readonly Dispatcher dispatcher;

        public CloudClientFactory()
            : this(PhoneApplicationService.Current.State, IsolatedStorageSettings.ApplicationSettings, Application.Current.Resources, Deployment.Current.Dispatcher)
        {
        }

        public CloudClientFactory(IDictionary<string, object> phoneState, IDictionary<string, object> isolatedStorage, IDictionary<object, object> appResources, Dispatcher dispatcher)
        {
            this.phoneState = phoneState;
            this.isolatedStorage = isolatedStorage;
            this.appResources = appResources;
            this.dispatcher = dispatcher;

            // Initialize the PushContext.Current instance.
            if (PushContext.Current == null)
            {
                new PushContext(
                    this.appResources["PushChannelName"].ToString(),
                    this.appResources["PushServiceName"].ToString(),
                    new[] { new Uri("https://127.0.0.1") },
                    this.dispatcher);
            }
        }

#if ACS
        public SL.Phone.Federation.Utilities.RequestSecurityTokenResponseStore TokenStore
        {
            get
            {
                return this.appResources["rstrStore"] as SL.Phone.Federation.Utilities.RequestSecurityTokenResponseStore;
            }
        }
#else
        public string UserName
        {
            get
            {
                return this.GetValue<string>("UserName");
            }
        }

        public string AuthenticationToken
        {
            get
            {
                return this.GetValue<string>("AuthenticationToken");
            }
        }
#endif

        public ISamplePushUserRegistrationClient ResolvePushNotificationClient()
        {
            return new SamplePushUserRegistrationClient(new Uri(this.appResources["PushNotificationServiceEndpoint"].ToString()), this.ResolveStorageCredentials(), this.appResources["ApplicationId"].ToString());
        }

        public DataServiceContext ResolveOdataServiceContext()
        {
            var serviceUri = new Uri(this.appResources["SqlOdataEndpoint"].ToString());
            var context = new DataServiceContext(serviceUri);

            context.SendingRequest += (s, e) =>
            {
                var credentials = this.ResolveStorageCredentials();

                credentials.AddAuthenticationHeadersLite(e.RequestData, e.RequestHeaders);
            };

            return context;
        }

#if ACS

        public IStorageCredentials ResolveStorageCredentials()
        {
            return new StorageCredentialsSwtToken(
                this.TokenStore.SecurityToken,
                this.TokenStore.RequestSecurityTokenResponse != null ? this.TokenStore.RequestSecurityTokenResponse.expires : 0);
        }

        public IRegistrationClient ResolveRegistrationClient()
        {
            return new RegistrationClient(this.appResources["RegistrationServiceEndpoint"].ToString(), this.ResolveStorageCredentials());
        }

        public void CleanAuthenticationToken()
        {
            // Remove the authentication token from the phone state dictionary.
            if (this.TokenStore.ContainsValidRequestSecurityTokenResponse())
            {
                this.TokenStore.RequestSecurityTokenResponse = null;
            }
        }
#else

        public IStorageCredentials ResolveStorageCredentials()
        {
            return new StorageCredentialsAuthToken(this.AuthenticationToken);
        }

        public IAuthenticationClient ResolveAuthenticationClient()
        {
            return new AuthenticationClient(this.appResources["AuthenticationServiceEndpoint"].ToString());
        }

        public void VerifyLoggedIn(Action userAlreadyLoggedInCallback, Action userNotLoggedInCallback)
        {
            var authToken = this.AuthenticationToken;
            if (string.IsNullOrEmpty(authToken))
            {
                this.dispatcher.BeginInvoke(() => userNotLoggedInCallback());
                return;
            }

            this.ResolveAuthenticationClient().Validate(
                authToken,
                args =>
                {
                    this.dispatcher.BeginInvoke(() => userAlreadyLoggedInCallback());
                },
                args =>
                {
                    this.dispatcher.BeginInvoke(() => userNotLoggedInCallback());
                });
        }

        public void SetUserName(string userName, bool persist = false)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException("userName", "The userName cannot be null nor empty.");
            }

            this.SaveValue(userName, "UserName", persist);
        }

        public void SetAuthenticationToken(string authToken, bool persist = false)
        {
            if (string.IsNullOrEmpty(authToken))
            {
                throw new ArgumentNullException("authToken", "The authentication token cannot be null nor empty.");
            }

            this.SaveValue(authToken, "AuthenticationToken", persist);
        }

        public void CleanAuthenticationToken()
        {
            // Remove the authentication token from the phone state dictionary.
            if (this.phoneState.ContainsKey("AuthenticationToken"))
            {
                this.phoneState.Remove("AuthenticationToken");
            }

            // Remove the authentication token from the phone isolated storage.
            if (this.isolatedStorage.ContainsKey("AuthenticationToken"))
            {
                this.isolatedStorage.Remove("AuthenticationToken");
            }
        }

        private void SaveValue(object value, string key, bool persist)
        {
            // Save the value in the phone application state.
            if (this.phoneState.ContainsKey(key))
            {
                this.phoneState.Remove(key);
            }

            this.phoneState.Add(key, value);

            if (persist)
            {
                // Persist the value in the phone isolated storage.
                this.isolatedStorage[key] = value;
            }
            else
            {
                // Remove old value from the phone isolated storage.
                if (this.isolatedStorage.ContainsKey(key))
                {
                    this.isolatedStorage.Remove(key);
                }
            }
        }

        private T GetValue<T>(string key)
        {
            if (this.phoneState.ContainsKey(key))
            {
                // Get the value from the phone application state.
                return (T)this.phoneState[key];
            }

            if (this.isolatedStorage.ContainsKey(key))
            {
                // Get the value from the phone isolated storage.
                return (T)this.isolatedStorage[key];
            }

            return default(T);
        }
#endif
    }
}
